package com.my.study.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author: yidujun
 * @create: 2022/03/28 20:59
 */
@Slf4j
public class SignUtils {

    /**
     * 构建签名
     *
     * @param params    参数
     * @param appSecret 密钥
     * @return 1签名
     */
    public static String createSign(Map<String, Object> params, String appSecret) {
        if (CollUtil.isEmpty(params)) {
            return "";
        }
        Set<String> keySet = params.keySet();
        List<String> paramsNames = new ArrayList<>(keySet);
        // 升序
        Collections.sort(paramsNames);
        // 拼接
        StringBuilder sb = new StringBuilder();
        for (String paramsName : paramsNames) {
            Object value = params.get(paramsName);
            if (null != value && StrUtil.isNotBlank(value.toString())) {
                sb.append(paramsName).append(value);
            }
        }
        String source = appSecret + sb.toString() + appSecret;
        String encrypt = "";
        try {
            encrypt = DigestUtil.md5Hex(source.getBytes(StandardCharsets.UTF_8)).toUpperCase();
//            encrypt = AESUtils.encrypt(appSecret, URLEncoder.encode(source, StandardCharsets.UTF_8.name()));
        } catch (Exception e) {
            log.error("构建签名错误，params={}", params, e);
        }
        return encrypt;
    }

    public static void main(String[] args) {
        Map<String, Object> params = new HashMap<>();
        params.put("qym_appKey", "KxcxC65I");
        params.put("qym_timestamp", "1648468641397");
        System.out.println(createSign(params, "8d75cf362226bc59a831f304149ac114dcff16bd"));

//        System.out.println(DigestUtil.md5Hex("helloworld".getBytes(StandardCharsets.UTF_8)).toUpperCase());

    }

}
